// 主题管理器
class ThemeManager {
    constructor() {
        this.currentTheme = this.getStoredTheme() || this.getSystemTheme();
        this.init();
    }

    // 获取系统主题偏好
    getSystemTheme() {
        return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    }

    // 从localStorage获取存储的主题
    getStoredTheme() {
        return localStorage.getItem('theme');
    }

    // 保存主题到localStorage
    saveTheme(theme) {
        localStorage.setItem('theme', theme);
    }

    // 应用主题
    applyTheme(theme) {
        document.documentElement.setAttribute('data-theme', theme);
        this.currentTheme = theme;
        this.saveTheme(theme);
        this.updateThemeToggleButton();
    }

    // 切换主题
    toggleTheme() {
        const newTheme = this.currentTheme === 'light' ? 'dark' : 'light';
        this.applyTheme(newTheme);
    }

    // 更新主题切换按钮状态
    updateThemeToggleButton() {
        const themeToggle = document.querySelector('.theme-toggle');
        if (themeToggle) {
            const icon = themeToggle.querySelector('i');
            if (icon) {
                icon.className = this.currentTheme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
            }
            // 使用多语言翻译
            const langManager = window.langManager;
            if (langManager) {
                const currentLang = langManager.getCurrentLanguage();
                const translations = {
                    zh: {
                        light: '切换到浅色模式',
                        dark: '切换到深色模式'
                    },
                    en: {
                        light: 'Switch to Light Mode',
                        dark: 'Switch to Dark Mode'
                    }
                };
                const title = this.currentTheme === 'dark' 
                    ? translations[currentLang].light 
                    : translations[currentLang].dark;
                themeToggle.setAttribute('title', title);
            }
        }
    }

    // 初始化主题
    init() {
        this.applyTheme(this.currentTheme);
        
        // 监听系统主题变化
        window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
            if (!this.getStoredTheme()) {
                this.applyTheme(e.matches ? 'dark' : 'light');
            }
        });
    }

    // 获取当前主题
    getCurrentTheme() {
        return this.currentTheme;
    }
}